<?php namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Models\Order;

class WeChatSendDelivery extends Command {

    protected $name = 'WeChatSendDelivery';//命令名称

    protected $description = '订单微信发货'; // 命令描述，没什么用

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->config = [
            // 必要配置
            'app_id'             => env('PUSHER_APP_ID'),
            'app_secret'         => env('PUSHER_APP_SECRET'),
            'mch_id'             => env('PUSHER_MCH_ID'),
            'key'                => env('PUSHER_MCH_SECRET_KEY'),   // API 密钥
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => public_path('/wechat/apiclient_cert.pem'), // XXX: 绝对路径！！！！
            'key_path'           => public_path('/wechat/apiclient_key.pem'),      // XXX: 绝对路径！！！！
            'notify_url'         => env('APP_URL').'/api/payNotify',     // 你也可以在下单时单独设置来想覆盖它
        ];

        $list = Order::where('is_send_delivery',1)
            ->with(['memberItem' => function($qeery){
                $qeery->select(['id','openid']);
            }])
            ->take(10)
            ->get(['id','transaction_id','mid','is_send_delivery'])
            ->toArray();
        try{
            if($list){

                foreach ($list as $item){
                    $update = Order::where('id', $item['id'])->update(['is_send_delivery'=>2]);
                    if($update){
                        $this->sendDelivery($item['transaction_id'], $item['member_item']['openid']);
                    }

                }

            }
        }catch(\Exception $e){
            Log::channel('WeChatSendDelivery')->info('微信发货订单任务失败：'.$e->getMessage());
        }

    }


    //获取token
    public function getAccessToken()
    {

        $cacheKey = $this->config['app_id'] . '@access_token';
        $appId = $this->config['app_id'];
        $appSecret = $this->config['app_secret'];

        if (!Cache::get($cacheKey)) {
            // 请求API获取 access_token
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";

            $http = new \GuzzleHttp\Client;
            $result = $http->get($url);
            $data = json_decode((string) $result->getBody(), true);

            //$data = json_decode($result, true);
            // 写入缓存

            Cache::add($cacheKey, $data['access_token'], 5000);    // 7000
        }
        return Cache::get($cacheKey);
    }


    public function stable_token()
    {
        $appId = $this->config['app_id'];
        $appSecret = $this->config['app_secret'];
        $grant_type = 'client_credential';
        $token_param = array(
            'grant_type' => $grant_type,
            'appid' => $appId,
            'secret' => $appSecret,
        );
        $url = "https://api.weixin.qq.com/cgi-bin/stable_token";
        $dataRes = curlPost($url, json_encode($token_param),1);
        $data = json_decode($dataRes, true);
        return $data['access_token'];
    }

    // 发货接口
    private function sendDelivery($transaction_id , $openid)
    {

        //$token = $this->getAccessToken();
        $token = $this->stable_token();

        $data = [
            'order_key' => [
                'order_number_type' => 2,
                'transaction_id' => $transaction_id
            ],
            'logistics_type' => 2,//物流模式，发货方式枚举值：1、实体物流配送采用快递公司进行实体物流配送形式 2、同城配送 3、虚拟商品，虚拟商品，例如话费充值，点卡等，无实体配送形式 4、用户自提
            'delivery_mode' => 1,
            'shipping_list' => [
                [
                    'tracking_no' => '',
                    'express_company' => '',
                    'item_desc' => '桶装水已送达'
                ]
            ],
            'upload_time' => date('Y-m-d\TH:i:sP', time()),
            'payer' => [
                'openid' => $openid
            ]
        ];

        $urlss = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=" . $token;
        //var_dump($urlss);
        $data = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        $results = curlPost($urlss, $data, 1);

        $results = json_decode($results, true);
        if ($results['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }


}
